﻿using Gl_mes.DAL.MesDB;
using Gl_mes.DAL.RoleDB;
using Gl_mes.View;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.SqlServer;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Gl_mes.BLL.Mes
{
    public class OrderCompletionControler
    {
        /// <summary>
        /// 查询是否存在
        /// </summary>
        /// <param name="searchList"></param>
        /// <returns></returns>
        public OrderCompletion IsExistsOrderCompletion(List<OrderCompletion> searchList)
        {
            OrderCompletion resBean = null;
            using (RoleDB ctx = new RoleDB())
            { 
                DateTime tmpDay = DateTime.Now;
                List<OrderCompletion> tmpList = ctx.OrderCompletion.ToList();
                foreach (OrderCompletion item in searchList)
                {
                    var query = tmpList.Where(o => o.track_number == item.track_number && o.prod_number == item.prod_number && o.goods_number == item.goods_number)
                                        .Where(o => ((DateTime)o.create_date).ToShortDateString() == tmpDay.ToShortDateString());
                    if (query != null && query.Count() > 0)
                    {
                        resBean = query.First();
                        break;
                    }
                }
            }
            return resBean;
        }

        /// <summary>
        /// 根据条件查询订单完成情况信息
        /// </summary>
        /// <param name="order"></param>
        /// <returns></returns>
        public List<OrderCompletion> SearchOrderByCondition(OrderCompletion order)
        {
            List<OrderCompletion> resList = new List<OrderCompletion>();
            using (RoleDB ctx = new RoleDB())
            {
                resList = ctx.OrderCompletion.ToList();
                if (order.prod_line != null && order.prod_line.Trim().Length > 0)
                {
                    resList = resList.Where(o => o.prod_line.Equals(order.prod_line)).ToList();
                }
                if (order.track_number != null && order.track_number.Trim().Length > 0)
                {
                    resList = resList.Where(o => o.track_number.Equals(order.track_number)).ToList();
                }
                if (order.prod_number != null && order.prod_number.Trim().Length > 0)
                {
                    resList = resList.Where(o => o.prod_number.Equals(order.prod_number)).ToList();
                }
                if (order.goods_number != null && order.goods_number.Trim().Length > 0)
                {
                    resList = resList.Where(o => o.goods_number.Equals(order.goods_number)).ToList();
                }
                if (order.order_number != null && order.order_number.Trim().Length > 0)
                {
                    resList = resList.Where(o => o.order_number.Equals(order.order_number)).ToList();
                }
                if (order.create_date.HasValue)
                {
                    resList = resList.Where(o => ((DateTime)o.create_date).ToShortDateString() == ((DateTime)order.create_date).ToShortDateString()).ToList();
                }
            }
            return resList;
        }

        /// <summary>
        /// 新增订单完成状况信息
        /// </summary>
        /// <param name="orderList"></param>
        /// <returns></returns>
        public int InsertOrderCompletion (List<OrderCompletion> orderList)
        {
            int count = 0;
            if (orderList != null && orderList.Count > 0)
            {
                using (RoleDB ctx = new RoleDB())
                {
                    foreach (OrderCompletion item in orderList)
                    {
                        item.create_date = DateTime.Now;
                        item.create_user = MainFrm.LoginUser.user_name;
                        ctx.OrderCompletion.Add(item);
                    }
                    count = ctx.SaveChanges();
                }
            }
            return count;
        }


        /// <summary>
        /// 更新订单完成状况信息
        /// </summary>
        /// <param name="orderList"></param>
        /// <returns></returns>
        public int UpdateOrderCompletion(List<OrderCompletion> orderList)
        {
            int count = 0;
            if (orderList != null && orderList.Count > 0)
            {
                using (RoleDB ctx = new RoleDB())
                {
                    foreach (OrderCompletion item in orderList)
                    {
                        ctx.OrderCompletion.Attach(item);
                        ctx.Entry(item).Property("clear_qty").IsModified = true;
                        ctx.Entry(item).Property("err_qty").IsModified = true;
                        ctx.Entry(item).Property("surp_qty").IsModified = true;
                    }
                    count = ctx.SaveChanges();
                }
            }
            return count;
        }


        /// <summary>
        /// 查询所有尚未完成的订单
        /// </summary>
        /// <returns></returns>
        public List<OrderCompletion> SearchNotCompOrder()
        {
            List<OrderCompletion> orderList = new List<OrderCompletion>();
            using (RoleDB ctx = new RoleDB())
            {
                var query = ctx.OrderCompletion.Where(o => o.order_qty > o.clear_qty);
                if (query != null && query.Count() > 0)
                {
                    orderList = query.ToList<OrderCompletion>();
                }
            }
            return orderList;
        }


        /// <summary>
        /// 查询所有订单
        /// </summary>
        /// <returns></returns>
        public List<OrderCompletion> SearchAllOrder()
        {
            List<OrderCompletion> resList = new List<OrderCompletion>();
            using (RoleDB ctx = new RoleDB())
            {
                resList = ctx.OrderCompletion.OrderByDescending(o => o.clear_qty).ToList<OrderCompletion>();
            }
            return resList;
        }


        /// <summary>
        /// 查询所有生产线
        /// </summary>
        /// <returns></returns>
        public List<string> SearchAllProdLine()
        {
            List<string> lineList = new List<string>();
            using (RoleDB ctx = new RoleDB())
            {
                var query = ctx.ProdLine;
                if (query != null && query.Count() > 0)
                {
                    foreach (var line in query)
                    {
                        lineList.Add(line.prod_line);
                    }
                }
            }
            return lineList;
        }

        public ProdLine SearchProdLineByName(string lineName)
        {
            using (RoleDB ctx = new RoleDB())
            {
                var query = ctx.ProdLine.Where(l => l.prod_line.Equals(lineName));
                if (query != null && query.Count() > 0)
                {
                    return query.First<ProdLine>();
                }
                else
                {
                    return null;
                }
            }
        }


        public List<StandardUpph> SearchStandUpphForYM(string ym, string line)
        {
            List<StandardUpph> resList = new List<StandardUpph>();
            using (RoleDB ctx = new RoleDB())
            {
                var query = from a in ctx.StandardUpph
                            join b in ctx.ProdLine on a.ProdLineID equals b.id into tmp
                            from ab in tmp.DefaultIfEmpty()
                            where a.YM == ym && ab.prod_line.Equals(line)
                            select new
                            {
                                a = a,
                                b = ab.prod_line
                            };
                if (query != null && query.Count() > 0)
                {
                    foreach (var item in query)
                    {
                        StandardUpph tmpBean = item.a;
                        tmpBean.ProdLineName = item.b;
                        resList.Add(tmpBean);
                    }
                }
            }
            return resList;
        }


        public List<RealityUpph> SearchRealityUpphForYM(int year, int month, string line)
        {
            List<RealityUpph> resList = new List<RealityUpph>();

            DateTime beginDay = new DateTime(year, month, 1, 0, 0, 0, 0);
            DateTime endDay = beginDay.AddMonths(1).AddDays(-1);
            using (RoleDB ctx = new RoleDB())
            {
                var query = from a in ctx.RealityUpph
                            join b in ctx.ProdLine on a.ProdLineID equals b.id into tmp
                            from ab in tmp.DefaultIfEmpty()
                            where a.FillDate >= beginDay && a.FillDate <= endDay && ab.prod_line.Equals(line)
                            select new
                            {
                                a = a,
                                b = ab.prod_line
                            };
                if (query != null && query.Count() > 0)
                {
                    foreach (var item in query)
                    {
                        RealityUpph tmpBean = item.a;
                        tmpBean.ProdLineName = item.b;
                        resList.Add(tmpBean);
                    }
                }
            }
            return resList;
        }


        public decimal SearchRealProductionByDate(string line, DateTime searchDay)
        {
            decimal prodQty = 0;
            using (RoleDB ctx = new RoleDB())
            {
                decimal tmpLen = 0;
                var query = ctx.OrderCompletion.Where(o => o.prod_line.Equals(line) && ((DateTime)DbFunctions.TruncateTime(o.create_date)) == searchDay && o.clear_qty > 0);
                if (query != null && query.Count() > 0)
                {
                    foreach (var item in query)
                    {
                        if (decimal.TryParse(item.goods_length, out tmpLen))
                        {
                            prodQty = prodQty + decimal.Parse(item.goods_length) * (decimal)item.clear_qty;
                        }
                    }
                }
            }
            return prodQty;
        }


        public int SaveStandUpph(List<StandardUpph> standList)
        {
            int count = 0;
            using (RoleDB ctx = new RoleDB())
            {
                if (standList != null && standList.Count > 0)
                {
                    foreach (var stand in standList)
                    {
                        if (stand.id > 0)
                        {
                            ctx.StandardUpph.Attach(stand);
                            ctx.Entry(stand).Property("Upph").IsModified = true;
                        }
                        else
                        {
                            ctx.StandardUpph.Add(stand);
                        }
                    }
                    count = ctx.SaveChanges();
                }
            }
            return count;
        }

        public int SaveRealUpph(List<RealityUpph> realList)
        {
            int count = 0;
            using (RoleDB ctx = new RoleDB())
            {
                if (realList != null && realList.Count > 0)
                {
                    foreach (var real in realList)
                    {
                        if (real.id > 0)
                        {
                            ctx.RealityUpph.Attach(real);
                            ctx.Entry(real).Property("Upph").IsModified = true;
                        }
                        else
                        {
                            ctx.RealityUpph.Add(real);
                        }
                    }
                    count = ctx.SaveChanges();
                }
            }
            return count;
        }


        public int DeleteOrderCompletion(List<OrderCompletion> orderList)
        {
            int count = 0;
            using (RoleDB ctx = new RoleDB())
            {
                if (orderList != null && orderList.Count > 0)
                {
                    foreach (var order in orderList)
                    {
                        var entity = ctx.OrderCompletion.Find(order.id);
                        ctx.OrderCompletion.Remove(entity);
                    }
                    count = ctx.SaveChanges();
                }
            }
            return count;
        }

        public List<StandardQC> SearchStandQCForYM(string ym)
        {
            List<StandardQC> resList = new List<StandardQC>();
            using (RoleDB ctx = new RoleDB())
            {
                var query = ctx.StandardQC.Where(q => q.YM == ym);
                if (query != null && query.Count() > 0)
                {
                    resList = query.ToList();
                }
            }
            return resList;
        }

        public List<RealityQC> SearchRealityQCForYM(int year, int month)
        {
            List<RealityQC> resList = new List<RealityQC>();

            DateTime beginDay = new DateTime(year, month, 1, 0, 0, 0, 0);
            DateTime endDay = beginDay.AddMonths(1).AddDays(-1);
            using (RoleDB ctx = new RoleDB())
            {
                var query = ctx.RealityQC.Where(q => q.FillDate >= beginDay && q.FillDate <= endDay);
                if (query != null && query.Count() > 0)
                {
                    resList = query.ToList();
                }
            }
            return resList;
        }

        public int SaveStandardQC(List<StandardQC> standList)
        {
            int count = 0;
            using (RoleDB ctx = new RoleDB())
            {
                if (standList != null && standList.Count > 0)
                {
                    foreach (StandardQC stand in standList)
                    {
                        if (stand.id <= 0)
                        {
                            if (stand.PassRate != 0)
                            {
                                ctx.StandardQC.Add(stand);
                            }
                        }
                        else
                        {
                            if (stand.PassRate == 0)
                            {
                                ctx.Entry(stand).State = EntityState.Deleted;
                            }
                            else
                            {
                                ctx.StandardQC.Attach(stand);
                                ctx.Entry(stand).State = EntityState.Modified; 
                            }
                        }
                    }
                    count = count + ctx.SaveChanges();
                }
            }
            return count;
        }

        public int SaveRealityQC(List<RealityQC> realList)
        {
            int count = 0;
            using (RoleDB ctx = new RoleDB())
            {
                if (realList != null && realList.Count > 0)
                {
                    foreach (RealityQC qc in realList)
                    {
                        if (qc.id > 0)
                        {
                            ctx.RealityQC.Attach(qc);
                            ctx.Entry(qc).State = EntityState.Modified;
                        }
                        else 
                        { 
                            ctx.RealityQC.Add(qc);
                        }
                    }
                    count = count + ctx.SaveChanges();
                }
            }
            return count;
        }


        /// <summary>
        /// 更新工单状态
        /// </summary>
        /// <param name="ppNo">工单单号</param>
        /// <param name="fillDate">工单的导入日期</param>
        /// <param name="status">状态</param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public int UpdateProdProcessStatus(string ppNo, DateTime fillDate,string status)
        {
            int count = 0;
            using (RoleDB ctx = new RoleDB())
            {
                //取得工单的后7位数字
                string tmpPP = ppNo.Trim().Substring(ppNo.Trim().Length - 7);
                //根据日期与后7位数字查找工单
                var query = ctx.OrderCompletion.Where(o => DbFunctions.TruncateTime(o.create_date) == DbFunctions.TruncateTime(fillDate))
                                                .Where(o => DbFunctions.Right(o.prod_number, 7) == tmpPP);
                if (query != null && query.Count() > 0)
                {
                    //找到工单后，根据状态调整未完成、异常与已完成数量
                    OrderCompletion tmpBean = query.First();
                    if (status.Equals("0") || status.Equals("未完成"))
                    {
                        tmpBean.clear_qty = 0;
                        tmpBean.err_qty = 0;
                        tmpBean.surp_qty = tmpBean.order_qty;
                    }
                    else if (status.Equals("1") || status.Equals("异常"))
                    {
                        tmpBean.clear_qty = 0;
                        tmpBean.err_qty = tmpBean.order_qty;
                        tmpBean.surp_qty = 0;
                    }
                    else if (status.Equals("2") || status.Equals("已完成"))
                    {
                        tmpBean.clear_qty = tmpBean.order_qty;
                        tmpBean.err_qty = 0;
                        tmpBean.surp_qty = 0;
                    }
                    //更新数据库资料
                    ctx.Entry<OrderCompletion>(tmpBean).State = EntityState.Modified;
                    count = ctx.SaveChanges();
                }
                else
                {
                    //如果没有找到工单，报异常
                    throw new Exception("没找到单号为：" + ppNo + "的工单！");
                }
            }
            return count;
        }
    }
}
